"use strict"

const fs = require('fs/promises');
const util = require('util');

class CodeWriter {
    blockStart = "{";
    blockEnd = "}";
    blockFromNewLine = false;
    indentStr = "\t";
    endOfLine = "";
    lines = "";
    fileMark = "";
    indent = 0;
    str = "";


    constructor(config/* : ICodeWriterConfig */) {
        if (!config) return;

        this.blockFromNewLine = !!config.blockFromNewLine;
        config.blockStart && (this.blockStart = config.blockStart);
        config.blockEnd && (this.blockEnd = config.blockEnd);
        config.fileMark && (this.fileMark = config.fileMark);
        config.endOfLine && (this.endOfLine = config.endOfLine);
    }

    writeMark() {

    }

    writeln(fmt/* : string */, ...args/* : any[] */) {
        if (!fmt) {
            this.str += "\n";
        } else {
            let newLine = this.blockFromNewLine ? "\n" : "";
            let startLine = this.str.length > 0 ? "\n" : "";
            this.str = this.str + startLine + this.currIndentStr + this.strFrame(fmt, ...args) + newLine;
        }
        return this;
    }

    writeContinue(fmt/* : string */, ...args/* : any[] */) {
        this.str += this.strFrame(fmt, ...args);
        return this;
    }

    startBlock() {
        let newLine = this.blockFromNewLine ? this.currIndentStr : "";
        this.str = this.str + newLine + this.blockStart;
        this.incIndent();
        return this;
    }

    endBlock() {
        this.decIndent();
        this.str = this.str + "\n" + this.currIndentStr + this.blockEnd;
        return this;
    }

    incIndent() {
        ++this.indent;
        return this;
    }

    decIndent() {
        --this.indent;
        return this;
    }

    reset() {
        this.indent = 0;
        this.str = "";
    }

    toString() {
        return this.str;
    }

    save(filePath/* : string */) {
        return fs.writeFile(filePath, this.str);
    }

    strFrame(str/* : string */, ...ages/* : any[] */) {
        for (let i = 0; i < ages.length; i++) {
            str = str.replace(`{${i}}`, ages[i]);
        }
        return str;
    }

    get currIndentStr() {
        if (this.indent < 1) return "";
        let str = "";
        for (let i = 0; i < this.indent; i++) {
            str += this.indentStr;
        }
        return str;
    }

}

module.exports = CodeWriter;